package com.iwdnb.gkgz.application.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.iwdnb.bmnf.common.service.CacheService;
import com.iwdnb.bmnf.common.utils.BeanConvertUtils;
import com.iwdnb.gkgz.application.service.RealTimeStockService;
import com.iwdnb.gkgz.application.service.source.NetsStockDataSource;
import com.iwdnb.gkgz.application.vo.RealtimeStockData;
import com.iwdnb.gkgz.application.vo.SimpleRealtimeStockData;
import com.iwdnb.gkgz.common.model.dto.Stock;
import com.iwdnb.gkgz.application.vo.StockConstants;
import com.iwdnb.gkgz.application.vo.StockStatus;
import com.iwdnb.gkgz.application.vo.StockType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author pengl
 * @date 2020/11/9
 */
@Component
public class RealTimeStockServiceImpl implements RealTimeStockService {

    @Autowired
    NetsStockDataSource dataSource;

    @Autowired
    CacheService cacheService;

    @Override
    public StockStatus getStockStatus() {
        return dataSource.getStockStatus();
    }

    @Override
    public Map<String,RealtimeStockData> getStockDataList(List<Stock> stocks) {
        return dataSource.getStockDataList(stocks);
    }

    @Override
    public RealtimeStockData getRealtimeData(String code, StockType type) {
        String stockKey = StockConstants.KEY_STOCK_REALTIME_DATA_PREFIX + code ;
        String simpleStockKey = StockConstants.KEY_STOCK_REALTIME_SIMPLE_DATA_PREFIX+code+":" ;
        RealtimeStockData realtimeStockData =  cacheService.get(stockKey);
        if(Objects.nonNull(realtimeStockData)){
            return realtimeStockData;
        }
         realtimeStockData = dataSource.getRealtimeData(code, type);
        if(realtimeStockData != null){
            cacheService.put(stockKey, realtimeStockData,3600);
            SimpleRealtimeStockData simpleRealtimeStockData = BeanConvertUtils.convert(realtimeStockData, SimpleRealtimeStockData.class);
            cacheService.put(simpleStockKey,simpleRealtimeStockData,3600);
        }


        return realtimeStockData;
    }
}
